package lk.asha.desktop.beans;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.*;
import javax.swing.JOptionPane;
import lk.asha.desktop.sms.COutgoingMessage;


/**
 * Class declaration
 *
 *
 * @author
 * @version 1.8, 08/03/00
 */
public class SimpleRead implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration	      portList;
    InputStream		      inputStream;
    SerialPort		      serialPort;
    Thread		      readThread;
    static OutputStream outputStream;
    static byte block[]=new byte[512];
    static int blockIndex=1;
    static int aaaa=1;
    static String fileName;
    static int fileIndex=0;



    public static void main(String[] args) {
    boolean		      portFound = false;
    
    String		      defaultPort = "COM16";//JOptionPane.showInputDialog("Enter Port...");

 	if (args.length > 0) {
	    defaultPort = args[0];
	}

	portList = CommPortIdentifier.getPortIdentifiers();

	while (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();
	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
		if (portId.getName().equals(defaultPort)) {
		    System.out.println("Found port: "+defaultPort);
		    portFound = true;
		    SimpleRead reader = new SimpleRead();
		}
	    }
	}
	if (!portFound) {
	    System.out.println("port " + defaultPort + " not found.");
	}

    }

    /**
     * Constructor declaration
     *
     *
     * @see
     */
    public SimpleRead() {
//
//        Loging loging=new Loging();
//        loging.setVisible(true);
         boolean		      portFound = false;

    String	   defaultPort = "COM16";//JOptionPane.showInputDialog("Enter Port...");



	portList = CommPortIdentifier.getPortIdentifiers();

	while (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();
	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
		if (portId.getName().equals(defaultPort)) {
		    System.out.println("Found port: "+defaultPort);
		    portFound = true;
        

        try {
            try {
                serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
            } catch (PortInUseException e) {
            }
            try {
                
                outputStream = serialPort.getOutputStream();
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {
            }
            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {
            }
            serialPort.notifyOnDataAvailable(true);
            try {
                serialPort.setSerialPortParams(19200, 8, 0, 0);
            } catch (UnsupportedCommOperationException e) {
            }
            try {
                readThread = new Thread(this);
                readThread.start();
            } catch (Exception e) {
            }
             outputStream.write("AT".getBytes());
             Thread.sleep(1000);
            outputStream.write(13);
          //  sendMassage("0714406266");

          //  Thread.sleep(1000);

            //outputStream.write("AT+CMGS=22".getBytes());
            //outputStream.write(13);
            //Thread.sleep(200);
            //outputStream.write("0011000A9170410426660000AA0AE8329BFD4697D9EC37".getBytes());
            //outputStream.write(26);
           // System.exit(5);

        }
        catch(Exception hu){
            
        }
    }

        }
    }
    }

    /**
     * Method declaration
     *
     *
     * @see
     */
    public void run() {
	try {
	    Thread.sleep(20000);
	} catch (InterruptedException e) {}
    }

    /**
     * Method declaration
     *
     *
     * @param event
     *
     * @see
     */
    public void serialEvent(SerialPortEvent event) {
	//    System.out.println("test");
	switch (event.getEventType()) {

	case SerialPortEvent.BI:

	case SerialPortEvent.OE:

	case SerialPortEvent.FE:

	case SerialPortEvent.PE:

	case SerialPortEvent.CD:

	case SerialPortEvent.CTS:

	case SerialPortEvent.DSR:

	case SerialPortEvent.RI:

	case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
	    break;

	case SerialPortEvent.DATA_AVAILABLE:
	    byte[] readBuffer = new byte[200];

	    try {
		while (inputStream.available() > 0) {
		    int numBytes = inputStream.read(readBuffer);
			System.out.print(new String(readBuffer));
            
//            Thread.sleep(1000);
//            outputStream.write(13);


      //      Thread thread=new Thread(new AddSMS(new String(readBuffer)));
      //      thread.start();



		}
        }
        catch (Exception e) {}

	}
    }
public static void sendMassage(String number, String message){
    String pduNo=""+eachNumber(number,1)+eachNumber(number,0)+eachNumber(number,3)+eachNumber(number,2)+eachNumber(number,5)+eachNumber(number,4)+eachNumber(number,7)+eachNumber(number,6)+eachNumber(number,9)+eachNumber(number,8);
    System.out.println(pduNo);
   // String message="q1111111111111111111111111111111111111111111111111111111";
   // Integer le=new Integer(message.length());
    String le=Integer.toHexString(message.length());
    COutgoingMessage cOutgoingMessage=new COutgoingMessage();
    message=cOutgoingMessage.textToPDU(message);
     String dm="001100A91"+pduNo+"0000AA0A"+message;
    System.out.println("\n\n\n\n\n@@@@@@@@@@@@@@@@@@@@@@@@@@@"+dm);
    System.out.println(message.length()+"\n\n\n\n\n\n\n\n");
    int a=message.length()/2+13;
    String hexVal=Integer.toHexString(message.length());
    System.out.println(hexVal);
        try {
            outputStream.write("AT".getBytes());
            outputStream.write(13);
            Thread.sleep(200);
            outputStream.write(("AT+CMGS="+a).getBytes());//+(4+message.length()))
            outputStream.write(13);
            Thread.sleep(200);

            outputStream.write(("0011000A91"+pduNo+"0000AA"+hexVal+message).getBytes());
           
       
          //   outputStream.write(("001100A91"+pduNo+"0000AA0A"+message).getBytes());//(("001100A91"+pduNo+"0000AA0A"+message).getBytes());
            outputStream.write(26);

//             Main m=new Main();
//        Sendsms c=new Sendsms(number, "xxxxxxx");
//        m.insertData("Customer",c);
        } catch (InterruptedException ex) {
            Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, ex);
        }
}
static String eachNumber(String no, int a){
String n=no.substring(a,++a);
System.out.println(n);
return  n;
}
}//end class





